package cn.lightpm.controller.account;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import cn.lightpm.dao.HibernateUtils;
import cn.lightpm.entity.account.Role;
import cn.lightpm.entity.account.User;
import cn.lightpm.service.account.AccountManager;
import cn.lightpm.util.hibernate.Page;
import cn.lightpm.util.hibernate.PropertyFilter;
import cn.lightpm.util.web.OptionalItem;
import cn.lightpm.util.web.SiteDefs;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private AccountManager accountManager;
	private Page<User> page = new Page<User>(20);

	/** 列表 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(HttpServletRequest request) {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		page = accountManager.searchUser(page, filters);
		return new ModelAndView("/account/user", "page", page);
	}
	
	/** 显示 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public ModelAndView show(@PathVariable Long id) {
		User user = accountManager.getUser(id);
		return new ModelAndView("/account/user-info", "user", user);
	}

	/** 进入新增 */
	@RequestMapping(value = "/new")
	public ModelAndView _new() {
		User user = new User();
		return new ModelAndView("/account/user-input", createModelForViewer(user));
	}	

	/** 进入编辑 */
	@RequestMapping(value = "/{id}/edit")
	public ModelAndView edit(@PathVariable Long id) {
		User user = accountManager.getUser(id);
		return new ModelAndView("/account/user-input", createModelForViewer(user));
	}		

	/** 保存新增 */
	@RequestMapping(value = "/new", method = RequestMethod.POST)
	public ModelAndView create(User user, Long[] checkedRoleIds) {
		saveUser(user, checkedRoleIds);
		return new ModelAndView(new RedirectView(SiteDefs.CONTEXT_NAME + "/user"));
	}

	/** 保存更新 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public ModelAndView update(User user, Long[] checkedRoleIds) throws Exception {
		saveUser(user, checkedRoleIds);
		return new ModelAndView(new RedirectView(SiteDefs.CONTEXT_NAME + "/user"));
	}

	/** 删除 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public ModelAndView delete(@PathVariable Long id) {
		accountManager.deleteUser(id);
		return new ModelAndView("/account/user");
	}
	
	/** 构造用于视图展现的Model数据 */
	private Map<String, Object> createModelForViewer(User user){
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("user", user);
		model.put("optionalRoles", createOptionalItemsForRole(user));
		return model;
	}
	
	/** 构造角色的选项列表 */
	private List<OptionalItem> createOptionalItemsForRole(User user){
		List<OptionalItem> items = new ArrayList<OptionalItem>();
		List<Role> selectedRoles = user.getRoleList();
		List<Role> allRoles = accountManager.getAllRole();
		for (Role role : allRoles){
			OptionalItem item = new OptionalItem(role.getId(), role.getName());
			item.setSelected(selectedRoles.contains(role));
			items.add(item);
		}
		return items;
	}
	
	/** 保存用户信息和相关的角色列表 */
	private void saveUser(User user, Long[] checkedRoleIds){
		if (checkedRoleIds == null){
			checkedRoleIds = new Long[0];
		}
		HibernateUtils.mergeByCheckedIds(user.getRoleList(), Arrays.asList(checkedRoleIds), Role.class);
		accountManager.saveUser(user);
	}
	
}